import axios from "axios";
import { message} from 'ant-design-vue';
import store from "@/store";
import router from "../router";
import * as responseStatus from '@/utils/constant.js';
const instance = axios.create({
  baseURL: '/',
  timeout: 600000
})

//请求拦截
instance.interceptors.request.use(
  config => {

    config.headers['token'] = store.getters['user/token'];
    config.headers['userId'] = store.getters['user/userId'];


    config.params = {
      ...config.params,
      _t: Date.parse(new Date()) / 1000
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  }

)

// 响应拦截
instance.interceptors.response.use(
  response => {
    const res = response.data
    // 下载文件直接返回
    if (res.type === 'application/octet-stream') {
      return response
    }

    if (res.type === 'application/vnd.ms-excel') {
      return response
    }

    if(typeof res !== 'object') {
      return res;
    }

    var url = response.config.url;

    if (res.code !== responseStatus.SUCCESS) {

      if(!url.startsWith('/user/getUserInfoByToken')){
          message.error({
            content: res.data ? res.data : "异常错误",
            duration: 2
          })
      }
      
      //登陆超时
      if (res.code === responseStatus.LOGIN_TIMEOUT) {
        // to re-login

        store.dispatch('user/resetToken').then(() => {
          setTimeout(() => {
            // location.reload();
          },1000)
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error);
    if(typeof error === 'string' && error.indexOf('canceled')){
      return ;
    }
    // router.push({path: '/500'});
    // message.error({
    //   content: error.message,
    //   duration: 2
    // })
    // return Promise.reject(error)
  }
)


/**
 * 上传
 * @param url
 * @param data
 * @param config
 */
export function upload(url, file, data ,config) {
  const formData = new FormData()
  formData.append('file', file)

  // config.headers['token'] = store.state.user.token | ''
  // 附加数据
  if (data) {
    Object.keys(data).forEach((key) => {
      formData.append(key, data[key])
    })
  }

  return new Promise((resolve, reject) => {

    instance
    .post(url,formData,config)
    .then(response => {

      resolve(response)
    }).catch(err => {

      reject(err)
    })
  })
}

/**
 * 下载
 * @param url
 * @param data
 */
export function download(url, data, fileName) {
  return new Promise((resolve, reject) => {
    // 打开
    // const loading = ElLoading.service({
    //   text: '正在下载数据...',
    //   background: 'rgba(0, 0, 0, 0.7)'
    // })

    instance.request({
      url: url,
      method: 'post',
      data: data,
      timeout: 1200000,
      responseType: 'blob'
    }).then(res => {
      // loading.close()

      // 文件下载
      const blob = new Blob([res.data], {
        type: 'application/vnd.ms-excel'
      })

      // 获得文件名称
      let link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', fileName)
      link.click()
      link = null
      message.success({
        content: '导出成功!',
        duration: 2
      })
    }).catch(err => {
      // loading.close()
      reject(err)
    })
  })
}


/**
 * get请求
 * @param {*} url 
 * @returns 
 */
export function get(url) {
  return new Promise((resolve, reject) => {
    instance.get(url)
      .then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })

  })
}

/**
 * post请求
 * @param {*} url 
 * @param {*} data 
 * @returns 
 */
export function post(url, data) {
  return new Promise((resolve, reject) => {
    instance.post(url, data)
      .then(res => {
        resolve(res)
      }, err => {
        reject(err)
      })
  })
}